package com.forg.mvc.core.container;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.forg.mvc.core.annotation.Interceptor;
import com.forg.mvc.core.common.ClassUtil;

public class InterceptorCntr {

    
    private static List<Class<?>> interceptorClassList = new ArrayList<>();
    
    //单例 非线程安全
    public static Map<Class<?>, Object> interceptorInstance = new HashMap<>();
    
    private static Logger logger = LoggerFactory.getLogger(InterceptorCntr.class);
    
    public synchronized static boolean init(){
        
        if(interceptorClassList.isEmpty()){
            
            interceptorClassList = ClassUtil.getAnnotationClassList(Interceptor.class);
            
            if(interceptorClassList==null){
                interceptorClassList = new ArrayList<>();
            }
            
            return !interceptorClassList.isEmpty();
        }
        
        return true;
    }
    
    public static List<Class<?>> getInterceptorClassList() {
        return interceptorClassList;
    }
    
    @SuppressWarnings("unchecked")
    public static <T> T getInstance(Class<T> clazz){
        if(interceptorInstance.get(clazz) == null){
            try {
                T t = clazz.newInstance();
                interceptorInstance.put(clazz, t);
                
                logger.debug("create interceptor {} instance success.",clazz.getName());
                return t;
            } catch (Exception e) {
                throw new RuntimeException("instance interceptor error!",e);
            }
        }else{
            return (T)interceptorInstance.get(clazz);
        }
    }
    
}
